<template>
  <view class="com-page">
    <video
      :id="`video-${props.index}`"
      class="video"
      object-fit="cover"
      :loop="true"
      :controls="false"
      :muted="true"
      :show-center-play-btn="false"
      :src="props.video"
    />
  </view>
</template>
<script setup lang="ts">
/**
 * 模块引入
 */
import {
  reactive,
  getCurrentInstance,
  onMounted,
  watchEffect,
  nextTick,
} from "vue";
const { proxy } = getCurrentInstance();
/**
 * 接口
 */
/**
 * 父组件数据
 */
const props = defineProps({
  index: {
    type: Number,
    defalut: 0,
  },
  scrollTop: {
    type: Number,
    defalut: 0,
  },
  video: {
    type: String,
    default: "",
  },
});
/**
 * 数据
 */
const data = reactive({
  query: {},
  top: 0,
  playing: false,
  systemInfo: {},
  videoHeight: 0,
  videoPlayHeight: 0,
});
/**
 * 初始方法
 */
onMounted(() => {
  init();
});

/**
 * 功能方法
 */
const init = () => {
  data.systemInfo = proxy.$config.systemInfo();
  data.query = uni.createSelectorQuery().in(getCurrentInstance());
  data.query
    .select(`#video-${props.index}`)
    .boundingClientRect((areaData: any) => {
      data.top = areaData.top;
      data.videoHeight = areaData.height;
      data.videoPlayHeight =
        data.top - data.systemInfo.screenHeight + areaData.height;
      handlePlay();
    })
    .exec();
};
const handlePlay = () => {
  if (
    props.scrollTop > data.videoPlayHeight &&
    props.scrollTop < data.top &&
    !data.playing
  ) {
    data.playing = true;
    play();
  } else if (
    props.scrollTop > data.top ||
    props.scrollTop < data.videoPlayHeight
  ) {
    data.playing = false;
    pause();
  }
};
const play = () => {
  let video = uni.createVideoContext(`video-${props.index}`, proxy);
  video.play();
};
const pause = () => {
  let video = uni.createVideoContext(`video-${props.index}`, proxy);
  video.pause();
};
/**
 * 父组件方法
 * const emit = defineEmits(['function']);
 * emit('function', data);
 */
/**
 * 父组件传递生命周期方法
 * onShareAppMessage  分享好友
 * onShareTimeline 分享朋友圈
 * onReachBottom 页面内触底
 */
watchEffect(() => {
  console.log(props.scrollTop);
  if (props.scrollTop) {
    handlePlay();
  }
});
</script>
<style lang="scss" scoped>
.com-page {
  .video {
    width: 100%;
    border-radius: 20rpx 20rpx 0 0;
  }
}
</style>
